//
//  ViewController.m
//  DomeTest
//
//  Created by l t on 2021/2/28.
//

#import "ViewController.h"
#import <AssetsLibrary/ALAsset.h>

#import <AssetsLibrary/ALAssetsLibrary.h>

#import <AssetsLibrary/ALAssetsGroup.h>

#import <AssetsLibrary/ALAssetRepresentation.h>

#import "TestViewController.h"


@interface ViewController ()
@property (nonatomic, strong) GPUImageVideoCamera *videoCamera; // 錄像
@property (nonatomic, strong) GPUImageMovieWriter *movieWriter; // 存錄像

@property (nonatomic, strong) UIButton *photoCaptureButton;
@property (nonatomic, strong) UIImageView *iv;
@property (nonatomic, strong) GPUImageBeautifyFilter *beautifyFilter;
@property (nonatomic, strong) NSArray *filterArray;
@property (nonatomic, strong) GPUImageFilterGroup *filterGroup;
@property (nonatomic, strong) GPUImageCropFilter *cropFilter;
@property (nonatomic, strong) GPUImageUIElement *uiElement; // 水印
@property (nonatomic, strong) GPUImageAlphaBlendFilter *uiFilter; // 水印
@property (nonatomic, strong) NSMutableArray *photoStyleImages;

@property (nonatomic, strong) UILabel *noticeLabel;
@property (nonatomic, strong) UIImageView *timeBGView;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) NSTimer *recordTimer;
@property (nonatomic, assign) NSInteger timerNum;
@property (nonatomic, assign) BOOL isRecording;

@property (nonatomic, strong) UIView *playerView;
//@property (nonatomic, strong) JXVideoPlayer *player;

@property (nonatomic, strong) UIButton *beautyBtn;
@property (nonatomic, strong) GPUImageBrightnessFilter *normalFilter;

@property (nonatomic,strong) NSString* outputFileName;//返回的video

@property (nonatomic, strong) UILabel *selectMusic;
//@property (nonatomic, strong) JXSelectMusicModel *selectMusicModel;
//@property (nonatomic, strong) JXAudioPlayer* audioPlayer;//选择音乐可以不要

@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) UIButton *completeBtn;
@property (nonatomic, strong) NSMutableArray* urlArray; // 录制多段视频url

@property (nonatomic, strong) NSTimer *exportTimer;
@property (nonatomic, strong) UIView *exportContent;
@property (nonatomic, strong) UILabel *exportPro;
@property (nonatomic, strong) AVAssetExportSession *exporter;   // 视频导出

//美颜/滤镜属性
@property (nonatomic, strong) UIView *baseView;
@property (nonatomic, strong) UIView *bigView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *bottomControlView;
@property (nonatomic, strong) UIButton *filterBtn;
@property (nonatomic, strong) UIButton *skinCareBtn;

@property (nonatomic, assign) BOOL isCreateFilter;
//// isRecoverHis = YES作用是 当前滤镜调整到正常后，要记录美颜中的磨皮和亮度的历史值
//@property (nonatomic, assign) BOOL isRecoverHis;
@property (nonatomic, strong) UISlider *bilateralSld;
@property (nonatomic, strong) UISlider *brightnessSld;

@property (nonatomic, assign) CGFloat bilHis;
@property (nonatomic, assign) CGFloat briHis;

@property (nonatomic, strong) GPUImageBilateralFilter *bilateralFilter;//  磨皮滤镜
@property (nonatomic, strong) GPUImageBrightnessFilter *brightnessFilter;// 美白滤镜
@property (nonatomic, strong) GPUImageToonFilter *toonfilter;
@property (nonatomic, strong) GPUImageFilter *filter;//滤镜
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationController pushViewController:[TestViewController new] animated:YES];
    
    _urlArray = [NSMutableArray array];
    
    _photoStyleImages = [NSMutableArray array];
    _isRecording = NO;
    
    if([self cameraCount]<=0){
        [self performSelector:@selector(dismissViewControllerAnimated:completion:) withObject:nil afterDelay:0.5];
//                [self dismissViewControllerAnimated:YES completion:nil];
        [g_App performSelector:@selector(showAlert:) withObject:@"相机" afterDelay:1];
        return;
    }
    
    // Yes, I know I'm a caveman for doing all this by hand
    GPUImageView *primaryView = [[GPUImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    primaryView.backgroundColor = [UIColor blackColor];
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(switchSkinCare)];
//    [primaryView addGestureRecognizer:tap];
    
    // 添加上下两个地方的透明模板
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, JX_SCREEN_WIDTH, THE_DEVICE_HAVE_HEAD ? 62 : 42)];
    UIView *botView = [[UIView alloc] initWithFrame:CGRectMake(0, JX_SCREEN_HEIGHT-90, JX_SCREEN_WIDTH, 90)];
    topView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    botView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [primaryView addSubview:topView];
    [primaryView addSubview:botView];
    
    //中间录制按钮
    _photoCaptureButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _photoCaptureButton.frame = CGRectMake(round(JX_SCREEN_WIDTH / 2.0 - 50.0 / 2.0), JX_SCREEN_HEIGHT - 70.0, 50.0, 50.0);
    [_photoCaptureButton setBackgroundImage:[UIImage imageNamed: @"start_video"] forState:UIControlStateNormal];
    [_photoCaptureButton addTarget:self action:@selector(takePhoto:) forControlEvents:UIControlEventTouchUpInside];
    [_photoCaptureButton setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    [primaryView addSubview:_photoCaptureButton];
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, JX_SCREEN_HEIGHT - 60.0, 30, 30)];
    [cancelBtn setImage:[UIImage imageNamed:@"fork"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [primaryView addSubview:cancelBtn];
    
    _completeBtn = [[UIButton alloc] initWithFrame:CGRectMake(JX_SCREEN_WIDTH - 50, JX_SCREEN_HEIGHT - 60.0, 35, 35)];
    _completeBtn.custom_acceptEventInterval = 1;
    [_completeBtn setImage:[UIImage imageNamed:@"complete"] forState:UIControlStateNormal];
    [_completeBtn addTarget:self action:@selector(completeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _completeBtn.hidden = YES;
    [primaryView addSubview:_completeBtn];
    
    UIButton *switchBtn = [[UIButton alloc] initWithFrame:CGRectMake(JX_SCREEN_WIDTH - 20 - 18, THE_DEVICE_HAVE_HEAD ? 32 : 12, 20, 20)];
    [switchBtn setImage:[UIImage imageNamed:@"switch_cammer"] forState:UIControlStateNormal];
    [switchBtn addTarget:self action:@selector(switchBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [switchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [primaryView addSubview:switchBtn];
    
    self.view = primaryView;
    
    //    GPUImageGaussianBlurFilter * blurFilter = [[GPUImageGaussianBlurFilter alloc] init];
    //    blurFilter.blurRadiusInPixels = 2.0;
    
    _beautifyFilter = [[GPUImageBeautifyFilter alloc] init];
    
    _videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
    _videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
    [_videoCamera addAudioInputsAndOutputs];
    _videoCamera.horizontallyMirrorFrontFacingCamera = NO; // 镜像
    [_videoCamera rotateCamera];
    
    //        CGFloat y = ((JX_SCREEN_HEIGHT - JX_SCREEN_WIDTH) / 2) / JX_SCREEN_HEIGHT;
    //        _cropFilter = [[GPUImageCropFilter alloc] initWithCropRegion:CGRectMake(0.0, y, 1.0,JX_SCREEN_WIDTH/(JX_SCREEN_HEIGHT - 160))];
    
    if (THE_DEVICE_HAVE_HEAD) {
        _cropFilter = [[GPUImageCropFilter alloc] initWithCropRegion:CGRectMake((1.0 - (480.0/640.0 - 0.13)) / 2, 0.0, 480.0/640.0 - 0.13,1.0)];
    }else {
        _cropFilter = [[GPUImageCropFilter alloc] initWithCropRegion:CGRectMake((1.0 - 480.0/640.0) / 2, 0.0, 480.0/640.0 ,1.0)];
    }
    
    //        [_videoCamera addTarget:_beautifyFilter];
    //        GPUImageView *filterView = (GPUImageView *)self.view;
    //        [_beautifyFilter addTarget:filterView];
    
    UIView *contentView = [[UIView alloc] initWithFrame:self.view.frame];
    contentView.backgroundColor = [UIColor redColor];
    UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
    logo.image = [UIImage imageNamed:@"ALOGO_120"];
    [contentView addSubview:logo];
    // 创建水印
    _uiElement = [[GPUImageUIElement alloc] initWithView:contentView];
    
    _uiFilter= [[GPUImageAlphaBlendFilter alloc] init];
    _uiFilter.mix = 1.0;
    
    [self setFilterGroup];
    
    if ( _videoCamera.inputCamera.hasFlash) {
        
        [_videoCamera.inputCamera lockForConfiguration:nil];
        _videoCamera.inputCamera.flashMode = AVCaptureFlashModeAuto;
        [_videoCamera.inputCamera unlockForConfiguration];
//        UIButton *flashBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, kDevice_Is_iPhoneX ? 32 : 12, 18, 18)];
//        [flashBtn setImage:[UIImage imageNamed:@"automatic"] forState:UIControlStateNormal];
//        [flashBtn addTarget:self action:@selector(flashBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//        [flashBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [primaryView addSubview:flashBtn];
    }
    
    _beautyBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, THE_DEVICE_HAVE_HEAD ? 32 : 12, 18, 18)];
    
    _beautyBtn.selected = NO;
    [_beautyBtn setImage:[UIImage imageNamed:@"camra_beauty"] forState:UIControlStateNormal];
    [_beautyBtn addTarget:self action:@selector(beautyBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_beautyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [primaryView addSubview:_beautyBtn];
    
   
    _iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, JX_SCREEN_WIDTH, JX_SCREEN_HEIGHT)];
    _iv.backgroundColor = [UIColor blackColor];
    _iv.contentMode = UIViewContentModeScaleAspectFill;
    _iv.userInteractionEnabled = YES;
    _iv.hidden = YES;
    [primaryView addSubview:_iv];
    UIButton *cancelImageBtn = [self createButtonWithFrame:CGRectMake(20, JX_SCREEN_HEIGHT-20-80, 80, 80)  image:@"video_return" action:@selector(cancelImageBtnAction:)];
    [_iv addSubview:cancelImageBtn];
    UIButton *confirmBtn = [self createButtonWithFrame:CGRectMake(JX_SCREEN_WIDTH-20-80, JX_SCREEN_HEIGHT-20-80, 80, 80) image:@"video_gou" action:@selector(confirmBtnAction:)];
    [_iv addSubview:confirmBtn];
    
    [self isVideoCustomView];
    [g_notify addObserver:self selector:@selector(didEnterBackground:) name:kApplicationDidEnterBackground object:nil];
}

- (void)setFilterGroup {
    /// 滤镜分组
    _filterGroup = [[GPUImageFilterGroup alloc] init];
    
//    [self videoSetFilter];

    //  磨皮滤镜
    GPUImageBilateralFilter *bilateralFilter = [[GPUImageBilateralFilter alloc] init];
    [_filterGroup addFilter:bilateralFilter];
    _bilateralFilter = bilateralFilter;
    //  美白滤镜
    GPUImageBrightnessFilter *brightnessFilter = [[GPUImageBrightnessFilter alloc] init];
    [_filterGroup addFilter:brightnessFilter];
    [_bilateralFilter setDistanceNormalizationFactor:MAXFLOAT];
    _brightnessFilter = brightnessFilter;
    //  设置滤镜组链
    [bilateralFilter addTarget:brightnessFilter];
    [_filterGroup setInitialFilters:@[bilateralFilter]];
    _filterGroup.terminalFilter = brightnessFilter;
    
    //    _beautifyFilter = [[GPUImageBeautifyFilter alloc] init];
    //    [_filterGroup addFilter:_beautifyFilter];
    // 添加滤镜
    GPUImageFilter*filter = [[GPUImageFilter alloc] init];
    [_filterGroup addTarget:filter];
    [filter addTarget:_cropFilter];
    _filter = filter;
    
    [_videoCamera addTarget:_filterGroup];
    [_filterGroup addTarget:(GPUImageView *)self.view];
    
    [_videoCamera startCameraCapture];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 离开时显示状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

- (void)actionQuit {
    [g_notify removeObserver:self];
//    [super actionQuit];
}

- (void)didEnterBackground:(NSNotification *)notif {
    if (_isRecording) {
        [self takePhoto:_photoCaptureButton];
    }
}

- (void)didAudioPlayBegin {
    
}

- (void)didAudioPlayEnd {
    
}

// X
- (void)cancelBtnAction:(UIButton *)btn {
//    [_audioPlayer stop];
//    _audioPlayer = nil;
    _isRecording = NO;
    [_recordTimer invalidate];
    
    _recordTimer = nil;
//    [g_navigation dismissViewController:self animated:YES];
    
    [[GPUImageContext sharedImageProcessingContext].framebufferCache purgeAllUnassignedFramebuffers];
    
    [self actionQuit];
}
// 转换摄像头
- (void)switchBtnAction:(UIButton *)btn {
    [_videoCamera rotateCamera];
}
// 重新拍照
- (void) cancelImageBtnAction:(UIButton *)btn {
    _iv.hidden = YES;
    _iv.image = nil;
    [[GPUImageContext sharedImageProcessingContext].framebufferCache purgeAllUnassignedFramebuffers];
}

// 确定此照片
- (void) confirmBtnAction:(UIButton *)btn {
    [self dismissViewControllerAnimated:YES completion:^{
        
//        if ([self.cameraDelegate respondsToSelector:@selector(cameraVC:didFinishWithImage:)]) {
//            [self.cameraDelegate cameraVC:self didFinishWithImage:_iv.image];
//        }
    }];
}

// 美颜按鈕
- (void) beautyBtnAction:(UIButton *)btn {
    
    if (!_baseView) {
        [self showBaseView];
    }
    [self setupBeautyView:YES];

//    [self switchSkinCare];
    return;
    
//    if (_isRecording) {
//        [JXMyTools showTipView:Localized(@"JX_CannotSwitchDuringRecording")];
//        return;
//    }
//
//    btn.selected = !btn.selected;
//
//    if (btn.selected) {
//        [btn setImage:[UIImage imageNamed:@"camra_beauty_close"] forState:UIControlStateNormal];
//        [_videoCamera removeAllTargets];
//        [_beautifyFilter removeAllTargets];
//        [_filterGroup removeAllTargets];
//        [_cropFilter removeAllTargets];
//        [_videoCamera addTarget:_cropFilter];
//        [_cropFilter addTarget:(GPUImageView *)self.view];
//
//    }else {
//        [btn setImage:[UIImage imageNamed:@"camra_beauty"] forState:UIControlStateNormal];
//
//        [_beautifyFilter removeAllTargets];
//
//        [_videoCamera removeAllTargets];
//        [_cropFilter removeAllTargets];
//        [_filterGroup removeAllTargets];
//        [self videoSetFilter];
//
//    }
}

#pragma mark Device Counts
- (NSUInteger) cameraCount
{
    return [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
}

// 设置录制视频filter
- (void)videoSetFilter{
    [_cropFilter addTarget:_beautifyFilter];
    
    [_filterGroup addTarget:_cropFilter];
    
    [_filterGroup addTarget:_beautifyFilter];
    
    [_filterGroup setInitialFilters:[NSArray arrayWithObject:_cropFilter]];
    
    [_filterGroup setTerminalFilter:_beautifyFilter];
    
    [_filterGroup forceProcessingAtSize:self.view.frame.size];
    
    [_filterGroup useNextFrameForImageCapture];
    
    [_videoCamera addTarget:_filterGroup];
    
    [_filterGroup addTarget:(GPUImageView *)self.view];
}
// 添加美颜风格
- (void) addPhotoStyle:(UIView *)parentView{
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, JX_SCREEN_WIDTH, 60)];
    _scrollView.backgroundColor = [UIColor clearColor];
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    [parentView addSubview:_scrollView];
    
    //    NSArray *nameArray = @[Localized(@"JX_Standard"),Localized(@"JX_Pale"),Localized(@"JX_Dark"),Localized(@"JX_Morning"),Localized(@"JX_Dusk"),Localized(@"JX_Natural"),Localized(@"JX_Highlight")];
    //
    //    _filterArray = @[
    //                     @{@"x":@1.1, @"y":@1.1},
    //                     @{@"x":@1.1, @"y":@0.5},
    //                     @{@"x":@0.9, @"y":@1.1},
    //                     @{@"x":@1.1, @"y":@1.3},
    //                     @{@"x":@1.1, @"y":@1.5},
    //                     @{@"x":@1.3, @"y":@1.1},
    //                     @{@"x":@1.5, @"y":@1.1},
    //                       ];
    //美颜
    GPUImageBeautifyFilter *BeautifyFilter = [[GPUImageBeautifyFilter alloc] init];
    //哈哈镜效果
    GPUImageStretchDistortionFilter *stretchDistortionFilter = [[GPUImageStretchDistortionFilter alloc] init];
    //黑白
    GPUImageGrayscaleFilter *GrayscaleFilter = [[GPUImageGrayscaleFilter alloc] init];
    //高斯模糊
    GPUImageGaussianBlurFilter  *GaussianBlurFilter = [[GPUImageGaussianBlurFilter  alloc] init];
    //边缘检测
    GPUImageXYDerivativeFilter *XYDerivativeFilter = [[GPUImageXYDerivativeFilter alloc] init];
    //怀旧
    GPUImageSepiaFilter *sepiaFilter = [[GPUImageSepiaFilter alloc] init];
    //反色
    GPUImageColorInvertFilter *invertFilter = [[GPUImageColorInvertFilter alloc] init];
    //饱和度
    GPUImageSaturationFilter *saturationFilter = [[GPUImageSaturationFilter alloc] init];
    // 亮度阈值
    GPUImageLuminanceThresholdFilter *LuminanceThresholdFilter = [[GPUImageLuminanceThresholdFilter alloc] init];
    //去雾
    GPUImageHazeFilter *HazeFilter = [[GPUImageHazeFilter alloc] init];
    //初始化滤镜数组
    self.filterArray = @[BeautifyFilter,stretchDistortionFilter,GrayscaleFilter,GaussianBlurFilter,XYDerivativeFilter,sepiaFilter,invertFilter,saturationFilter,LuminanceThresholdFilter,HazeFilter];
    
    NSArray *nameArray = @[@"正常",@"美颜",@"哈哈镜",@"黑白",@"高斯模糊",@"边缘检测",@"怀旧",@"反色",@"饱和度",@"亮度阈值",@"去雾"];
    UIImageView *lastImageView;
    for (NSInteger i = 0; i < nameArray.count; i ++) {
        //        NSDictionary *dict = _filterArray[i];
        UIImage *inputImage = [UIImage imageNamed:@"zhang"];
        
        //        GPUImagePicture *stillImageSource = [[GPUImagePicture alloc] initWithImage:inputImage];
        
        //        GPUImageHSBFilter *hsbFilter = [[GPUImageHSBFilter alloc] init];
        //        [hsbFilter adjustBrightness:[dict[@"x"] floatValue]];
        //        [hsbFilter adjustSaturation:[dict[@"y"] floatValue]];
        
        //        [stillImageSource addTarget:hsbFilter];
        //        [hsbFilter useNextFrameForImageCapture];
        //        [stillImageSource processImage];
        
        //        UIImage *image = [hsbFilter imageFromCurrentFramebuffer];
        
        if (i > 0) {
            [self.filterArray[i-1] useNextFrameForImageCapture];
            //获取数据源
            GPUImagePicture *stillImageSource=[[GPUImagePicture alloc]initWithImage:inputImage];
            [stillImageSource addTarget:self.filterArray[i-1]];
            //开始渲染
            [stillImageSource processImage];
            inputImage = [self.filterArray[i-1] imageFromCurrentFramebuffer];
        }

        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(lastImageView.frame) + 4, 0, 50, 60)];
        imageView.userInteractionEnabled = YES;
        imageView.tag = i;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectPhotoStyle:)];
        [imageView addGestureRecognizer:tap];
        
        imageView.image = inputImage;
        [_scrollView addSubview:imageView];
        lastImageView = imageView;
        
        if (i == 0) {
            imageView.layer.borderWidth = 2.0;
            imageView.layer.borderColor = [[UIColor yellowColor] CGColor];
        }
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.frame.size.height - 15, imageView.frame.size.width, 15)];
        label.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
        label.text = nameArray[i];
        label.font = [UIFont systemFontOfSize:12];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        [imageView addSubview:label];
        
        [_photoStyleImages addObject:imageView];
    }
    _scrollView.contentSize = CGSizeMake(CGRectGetMaxX(lastImageView.frame) + 10, 0);
}

- (UIButton *)createButtonWithFrame:(CGRect)frame image:(NSString *)image action:(SEL)action {
    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    button.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = button.frame.size.width/2;
    [button setImage:[UIImage scaleToSize:[UIImage imageNamed:image] size:CGSizeMake(32, 32)] forState:UIControlStateNormal];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    return button;
}
// 選擇美颜风格
- (void) selectPhotoStyle:(UIGestureRecognizer *)tap{
    
    if (_isRecording) {
        [JXMyTools showTipView:@"JX_CannotSwitchDuringRecording"];
        return;
    }
    
    if (_beautyBtn.selected) {
        [JXMyTools showTipView:@"JX_PleaseOpenBeauty"];
        return;
    }
    
    UIView *view = tap.view;
    self.isCreateFilter = YES;
    
    if (view == _photoStyleImages[1]) {
        [self recoverFilterGroup];
        [_bilateralSld setValue:self.bilHis > 0 ? self.bilHis : 4.2];
        [_brightnessSld setValue:self.briHis> 0 ? self.briHis : 0.07];
        [_bilateralFilter setDistanceNormalizationFactor:[self getBilValue:self.bilHis > 0 ? self.bilHis : 4.2]];
        _brightnessFilter.brightness = self.briHis> 0 ? self.briHis : 0.07;
        return;
    }else {
        [_bilateralSld setValue:0];
        [_brightnessSld setValue:0];
    }
    
    for (UIImageView *imageView in _photoStyleImages) {
        if (view == imageView) {
            imageView.layer.borderWidth = 2.0;
            imageView.layer.borderColor = [[UIColor yellowColor] CGColor];
        }else {
            imageView.layer.borderWidth = 0.0;
        }
    }
    [self.videoCamera removeAllTargets];
    if (view.tag >= 1) {
        GPUImageFilter *filter = self.filterArray[view.tag-1];
        [self.videoCamera addTarget:filter];
        [filter addTarget:(GPUImageView *)self.view];
        [filter addTarget:_cropFilter];
        self.filter = filter;
    }else {
        [self setFilterGroup];
    }

    
//    [_beautifyFilter removeAllTargets];
//
//    _beautifyFilter = [GPUImageBeautifyFilter alloc];
//
//    _beautifyFilter.dict = _filterArray[view.tag];
//
//    _beautifyFilter = [_beautifyFilter init];
//
//    [_videoCamera removeAllTargets];
//    [_cropFilter removeAllTargets];
//    [_filterGroup removeAllTargets];
//    [self videoSetFilter];

    
}


// 录制视频专有UI
- (void) isVideoCustomView{
    _noticeLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 0, JX_SCREEN_WIDTH-45*2, 45)];
    _noticeLabel.center = self.view.center;
    _noticeLabel.textColor = [UIColor whiteColor];
    _noticeLabel.font = [UIFont systemFontOfSize:15];
    _noticeLabel.numberOfLines = 2;
    _noticeLabel.backgroundColor = [UIColor clearColor];
    _noticeLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_noticeLabel];
    //    [_noticeLabel release];
    //    [self noticeLabelHidden:NO textType:1];
    
    //时间
    _timerNum = 0;
    _timeBGView = [[UIImageView alloc] initWithFrame:CGRectMake((JX_SCREEN_WIDTH-210)/2,  THE_DEVICE_HAVE_HEAD ? JX_SCREEN_TOP/2+5 : JX_SCREEN_TOP/2-15, 210, 2)];
    //    _timeBGView = [[UIImageView alloc] initWithFrame:CGRectMake((JX_SCREEN_WIDTH-210)/2, (JX_SCREEN_HEIGHT-JX_SCREEN_WIDTH)/2-35, 210, 2)];
    _timeBGView.image = [UIImage imageNamed:@"time_axis"];
//    [self.view addSubview:_timeBGView];
    
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(60, THE_DEVICE_HAVE_HEAD ? 40 : 20, JX_SCREEN_WIDTH - 120, 50)];
    _progressView.backgroundColor = [UIColor redColor];
    _progressView.progress = 0.0;
    [self.view addSubview:_progressView];
    
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 55, 30)];
    _timeLabel.center = _timeBGView.center;
    _timeLabel.text = @"00:00";
    _timeLabel.textAlignment = NSTextAlignmentCenter;
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.shadowColor  = [UIColor blackColor];
    _timeLabel.shadowOffset = CGSizeMake(1, 1);
    _timeLabel.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:_timeLabel];
    
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_timeLabel.frame) + 20, 100, 30)];
    btn.center = CGPointMake(self.view.center.x, btn.center.y);
    [btn addTarget:self action:@selector(selectMusicBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    _selectMusic = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    _selectMusic.font = [UIFont systemFontOfSize:14.0];
    _selectMusic.textColor = [UIColor redColor];
    _selectMusic.text = @"JX_ChooseMusic";
    _selectMusic.textAlignment = NSTextAlignmentCenter;
    [btn addSubview:_selectMusic];
    
    
    _exportContent = [[UIView alloc] initWithFrame:CGRectMake((JX_SCREEN_WIDTH - 100) / 2, (JX_SCREEN_HEIGHT - 100) /2, 100, 100)];
    _exportContent.backgroundColor = [UIColor clearColor];
    _exportContent.hidden = YES;
    [self.view addSubview:_exportContent];
    
    _exportPro = [[UILabel alloc] initWithFrame:CGRectMake((_exportContent.frame.size.width - 50) / 2, (_exportContent.frame.size.height - 50) /2 - 10, 50, 50)];
    _exportPro.layer.borderWidth = 2.0;
    _exportPro.layer.borderColor = [UIColor whiteColor].CGColor;
    _exportPro.layer.cornerRadius = 50 / 2;
    _exportPro.layer.masksToBounds = YES;
    _exportPro.text = @"100%";
    _exportPro.font = [UIFont systemFontOfSize:15.0];
    _exportPro.textAlignment = NSTextAlignmentCenter;
    _exportPro.textColor = [UIColor whiteColor];
    [_exportContent addSubview:_exportPro];
    
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_exportPro.frame) + 5, _exportContent.frame.size.width, 20)];
    tipLabel.text = @"JX_InTheCompression...";
    tipLabel.font = [UIFont systemFontOfSize:15.0];
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.textColor = [UIColor whiteColor];
    [_exportContent addSubview:tipLabel];
    
}

//- (void)selectMusicBtnAction:(UIButton *)btn {
//    if (_isRecording) {
//        [self takePhoto:_photoCaptureButton];
//    }
//    JXSelectMusicVC *vc = [[JXSelectMusicVC alloc]init];
//    vc.delegate = self;
//    [g_navigation pushViewController:vc animated:YES];
//}
//
//- (void)selectMusicVC:(JXSelectMusicVC *)vc selectMusic:(JXSelectMusicModel *)model{
//
//    _progressView.progress = 0.0;
//    [_urlArray removeAllObjects];
//    _timerNum = 0;
//    _completeBtn.hidden = YES;
//    self.selectMusic.text = model.name;
//    self.selectMusicModel = model;
//
//    _audioPlayer = [[JXAudioPlayer alloc]initWithParent:self.view frame:CGRectNull VoiceViewMoveType:VoiceViewMoveType_left];
//    _audioPlayer.isOpenProximityMonitoring = NO;
//    _audioPlayer.delegate = self;
//    _audioPlayer.didAudioPlayEnd = @selector(didAudioPlayEnd);
//    _audioPlayer.didAudioPlayBegin = @selector(didAudioPlayBegin);
//    _audioPlayer.didAudioOpen = @selector(didAudioOpen);
//    _audioPlayer.audioFile = [[NSString stringWithFormat:@"%@%@",g_config.downloadUrl,model.path] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//}

// 随时切换模式
- (void)switchSkinCare {
    self.scrollView.hidden = !self.scrollView.hidden;
    
}

- (void)completeBtnAction:(UIButton *)btn {
    
    _photoCaptureButton.enabled = NO;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _photoCaptureButton.enabled = YES;
    });
    
    [_photoCaptureButton setBackgroundImage:[UIImage imageNamed: @"start_video"] forState:UIControlStateNormal];
    [_recordTimer invalidate];
    _recordTimer = nil;
    [self endRecording];
    if (_isRecording) {
        
        [_urlArray addObject:[NSURL URLWithString:[NSString stringWithFormat:@"file://%@",self.outputFileName]]];
    }
    _isRecording = NO;
    _timerNum = 0;
    _timeLabel.text = @"00:00";
    
//    self.outputFileName = kCameraVideoPath;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self mergeAndExportVideos:_urlArray withOutPath:self.outputFileName];
        [_urlArray removeAllObjects];
        _completeBtn.hidden = YES;
        
    });
    
}
- (BOOL)checkCameraLimits{
    /// 先判断摄像头硬件是否好用
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        // 用户是否允许摄像头使用
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        // 不允许弹出提示框
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"JX_CameraNotTake" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * action = [UIAlertAction actionWithTitle:@"JXSettingVC_Set" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                // 无权限 引导去开启
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url];
                }
            }];
            UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"JX_Cencal" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alert addAction:action];
            [alert addAction:actionCancel];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                UIViewController *lastVC = (UIViewController *)g_navigation.subViews.lastObject;
//                [lastVC presentViewController:alert animated:YES completion:nil];
            });
            return NO;
        }else{
            // 这里是摄像头可以使用的处理逻辑
            return YES;
        }
    } else {
        // 硬件问题提示
//        [g_App showAlert:Localized(@"JX_CameraBad")];
        return NO;
    }
}
// 開始拍照、錄像
- (void)takePhoto:(UIButton *)btn;
{
    
    // 检测摄像头
    if (![self checkCameraLimits]) {
        return;
    }

    if (!_isRecording) {
        _outputFileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"tmp/Movie%lu.mov",(unsigned long)_urlArray.count]];
        [self.scrollView setHidden:YES];
        [_photoCaptureButton setBackgroundImage:[UIImage imageNamed:@"stop_video"] forState:UIControlStateNormal];
        _isRecording = YES;
        [self startPhoto];
//        if (_audioPlayer.audioFile.length > 0) {
//            [_audioPlayer switch];
//        }
        
        _progressView.progress = 0.0;
        _recordTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(recordTimerAction:) userInfo:nil repeats:YES];
        
        //            [self noticnoticeLabelHiddeneLabelHidden:YES textType:1];
    }else {
        [_recordTimer invalidate];
//        if (_audioPlayer.audioFile.length > 0) {
//            [_audioPlayer pause];
//        }
        [_photoCaptureButton setBackgroundImage:[UIImage imageNamed: @"start_video"] forState:UIControlStateNormal];
        _isRecording = NO;
        [self endRecording];
        [_urlArray addObject:[NSURL URLWithString:[NSString stringWithFormat:@"file://%@",self.outputFileName]]];
        
        //            [self.scrollView setHidden:NO];
        
//        if (_timerNum <= 0) {
//            return;
//        }
        
        
        //            [self dismissViewControllerAnimated:YES completion:^{
        //
        //                if ([self.cameraDelegate respondsToSelector:@selector(cameraVC:didFinishWithVideoPath:timeLen:)]) {
        //                    [self.cameraDelegate cameraVC:self didFinishWithVideoPath:self.outputFileName timeLen:self.timerNum];
        //                }
        //
        //                _timerNum = 0;
        //            }];
        
    }
}
- (void)savePhotoCmare:(NSString *)pathToMovie {

    NSURL *url = [[NSURL alloc] initFileURLWithPath:pathToMovie];

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    

    

    if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:url]) {

        [library writeVideoAtPathToSavedPhotosAlbum:url

                                    completionBlock:^(NSURL *assetURL, NSError *error){

                                        dispatch_async(dispatch_get_main_queue(), ^{

                                            if (error) {

                                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Video Saving Failed"  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil, nil];

                                                [alert show];

                                            }else{

                                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Video Saved" message:@"Saved To Photo Album"  delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];

                                                [alert show];

                                            }

                                            

                                        });

                                        

                                    }];

    }

    

}

- (void)didExitBtn:(id)sender {
    _playerView = nil;
//    _player = nil;
}


- (NSString *)getDataFilePath {
    NSString* s = [NSString stringWithFormat:@"%@/Library/Caches/",NSHomeDirectory()];
    //NSLog(@"%@",s);
    return s;
}

// 开始录制视频
- (void)startPhoto {
    
    ///录制的视频会存储到该路径下 唯一
    
    NSString *pathToMovie = _outputFileName;

    
    NSLog(@"%@",pathToMovie);
    
    unlink([pathToMovie UTF8String]);
    
    NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
    
    //    _movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(720, 720) fileType:AVFileTypeQuickTimeMovie outputSettings:nil];
    
    _movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(((int)JX_SCREEN_WIDTH/16)*16, ((int)JX_SCREEN_HEIGHT/16)*16) fileType:AVFileTypeQuickTimeMovie outputSettings:nil];
    
    AudioChannelLayout channelLayout;
    
    memset(&channelLayout, 0, sizeof(AudioChannelLayout));
    
    channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
    
    NSDictionary *audioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                   
                                   [ NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,//制定编码算法
                                   [ NSNumber numberWithInt: 2 ], AVNumberOfChannelsKey,//声道
                                   [ NSNumber numberWithFloat: 16000.0 ], AVSampleRateKey,//采样率
                                   [ NSData dataWithBytes:&channelLayout length: sizeof( AudioChannelLayout ) ], AVChannelLayoutKey,
                                   [ NSNumber numberWithInt: 32000 ], AVEncoderBitRateKey,//编码率
                                   
                                   nil];
    
    [_movieWriter setHasAudioTrack:YES audioSettings:audioSettings];
    _movieWriter.hasAudioTrack = YES;
    
    _movieWriter.encodingLiveVideo = YES;
    _movieWriter.shouldPassthroughAudio = YES;
    //    [_filterGroup addTarget:_movieWriter];
    
    [_videoCamera addAudioInputsAndOutputs];
    
    _videoCamera.audioEncodingTarget = _movieWriter;
    
//    if (_filterGroup.targets.count <= 0) {
//        [_cropFilter addTarget:_movieWriter];
//    }
//    else {
//        [_filterGroup addTarget:_movieWriter];
//    }
    [_cropFilter addTarget:_movieWriter];
    [_movieWriter startRecording];
    
}

// 录制视频计时
- (void)recordTimerAction:(NSTimer *)timer {
    _timerNum ++;
    NSInteger m = _timerNum/60;
    NSInteger n = _timerNum%60;
    NSString * labelTimeStr;
    labelTimeStr = [NSString stringWithFormat:@"%.2ld:%.2ld",m,n];
    _timeLabel.text = labelTimeStr;
    _completeBtn.hidden = NO;
    
    CGFloat f = 25;//录制视频时长
    // 后台配置时间
//    if ([g_config.videoLength intValue] > 0) {
//        f = [g_config.videoLength intValue];
//    }
    
    _progressView.progress = _timerNum / 100.0 / f;
    if (_timerNum / 100.0 / f >= 1.0) {
        [_recordTimer invalidate];
        _recordTimer = nil;
        _timerNum = 0;
//        [self takePhoto:_photoCaptureButton];
        [self completeBtnAction:_completeBtn];
    }
}

///完成录制
- (void)endRecording {
    
    [_movieWriter finishRecording];
    
    [_cropFilter removeTarget:_movieWriter];
    
    [_beautifyFilter removeTarget:_movieWriter];
    
    [_filterGroup removeTarget:_movieWriter];
    
    _videoCamera.audioEncodingTarget = nil;
    
        [self savePhotoCmare:_outputFileName];
    
}

- (void)mergeAndExportVideos:(NSArray*)videosPathArray withOutPath:(NSString*)outpath{
    if (videosPathArray.count == 0) {
        return;
    }
    //音频视频合成体
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
    
    //创建音频通道容器
    AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];
    //创建视频通道容器
    AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];

//    UIImage* waterImg = [UIImage imageNamed:@"ALOGO_120"];
    CMTime totalDuration = kCMTimeZero;
    for (int i = 0; i < videosPathArray.count; i++) {
        //        AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL URLWithString:videosPathArray[i]]];
        NSDictionary* options = @{AVURLAssetPreferPreciseDurationAndTimingKey:@YES};
        AVAsset* asset = [AVURLAsset URLAssetWithURL:videosPathArray[i] options:options];
        
        NSError *erroraudio = nil;
        //获取AVAsset中的音频 或者视频
        AVAssetTrack *assetAudioTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] firstObject];
        //向通道内加入音频或者视频
        BOOL ba = [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration)
                                      ofTrack:assetAudioTrack
                                       atTime:totalDuration
                                        error:&erroraudio];
        
        NSLog(@"erroraudio:%@%d",erroraudio,ba);
        NSError *errorVideo = nil;
        AVAssetTrack *assetVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo]firstObject];
        BOOL bl = [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration)
                                      ofTrack:assetVideoTrack
                                       atTime:totalDuration
                                        error:&errorVideo];
        
        NSLog(@"errorVideo:%@%d",errorVideo,bl);
        totalDuration = CMTimeAdd(totalDuration, asset.duration);
    }
    NSLog(@"%@",NSHomeDirectory());
    

    
    NSURL *mergeFileURL = [NSURL fileURLWithPath:outpath];
    
    
    _exportTimer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(exportTimerAction:) userInfo:nil repeats:YES];
    _exportContent.hidden = NO;
    _exportPro.text = @"0%";
    
    //视频导出工具
    _exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition
                                                                      presetName:AVAssetExportPreset1280x720];
    _exporter.outputURL = mergeFileURL;
    _exporter.outputFileType = AVFileTypeQuickTimeMovie;
    _exporter.shouldOptimizeForNetworkUse = YES;
    [_exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            

        });
        
        
    }];
    
}

- (void)exportTimerAction:(NSTimer *)timer {
    NSLog(@"exporter.progress = %f",_exporter.progress);
    
    NSString *str = [NSString stringWithFormat:@"%d%%",(int)(_exporter.progress * 100)];
    _exportPro.text = str;
    
    if (_exporter.progress >= 1) {
        [_exportTimer invalidate];
        _exportTimer = nil;
    }
}

- (void)showBaseView {
    self.baseView  = [[UIView alloc] initWithFrame:self.view.bounds];
    self.baseView.backgroundColor = [UIColor clearColor];
    self.baseView.hidden = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideBaseView)];
    [self.baseView addGestureRecognizer:tap];
    
    [self.view addSubview:self.baseView];
    
    self.bigView = [[UIView alloc] initWithFrame:CGRectMake(0, JX_SCREEN_HEIGHT-100-JX_SCREEN_BOTTOM, JX_SCREEN_WIDTH, 100+JX_SCREEN_BOTTOM)];
    self.bigView.backgroundColor = HEXCOLOR(0x323232);
    [self.baseView addSubview:self.bigView];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickBigView)];
    [self.bigView addGestureRecognizer:tap1];
    
    [self addPhotoStyle:self.bigView];
    [self initBottomView:self.bigView];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_scrollView.frame)+20, JX_SCREEN_WIDTH, .5)];
    line.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
    [self.bigView addSubview:line];
    
    
    //滤镜
    self.filterBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_scrollView.frame)+20, JX_SCREEN_WIDTH/2, JX_SCREEN_BOTTOM)];
    [self.filterBtn setTitle:@"JX_CameraFilter" forState:UIControlStateNormal];
    [self.filterBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.filterBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.filterBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [self.filterBtn addTarget:self action:@selector(didFilterBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.bigView addSubview:self.filterBtn];
    
    UIView *lineF = [[UIView alloc] initWithFrame:CGRectMake(self.filterBtn.frame.size.width-.5, 12, LINE_WH, 49-12*2)];
    lineF.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
    [self.filterBtn addSubview:lineF];
    
    //美颜
    self.skinCareBtn = [[UIButton alloc] initWithFrame:CGRectMake(JX_SCREEN_WIDTH/2, self.filterBtn.frame.origin.y, JX_SCREEN_WIDTH/2, self.filterBtn.frame.size.height)];
    [self.skinCareBtn setTitle:@"JX_CameraSkinCare" forState:UIControlStateNormal];
    [self.skinCareBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [self.skinCareBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.skinCareBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.skinCareBtn addTarget:self action:@selector(didBeautyBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.bigView addSubview:self.skinCareBtn];
    
}

- (void)setupBeautyView:(BOOL)isFilter {
    self.baseView.hidden = NO;
    _scrollView.hidden = !isFilter;
    _bottomControlView.hidden = isFilter;
    [self.filterBtn setSelected:isFilter];
    [self.skinCareBtn setSelected:!isFilter];
}


- (void)initBottomView:(UIView *)parentView
{
    _bottomControlView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, JX_SCREEN_WIDTH, 60)];
    [parentView addSubview:_bottomControlView];
    
    
    //磨皮
    UILabel *bilateralL = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 40, 25)];
    bilateralL.text = @"JX_CameraExfoliating";
    bilateralL.font = [UIFont systemFontOfSize:14];
    bilateralL.textColor = [UIColor whiteColor];
    [_bottomControlView addSubview:bilateralL];
    
    UISlider *bilateralSld  = [[UISlider alloc] initWithFrame:CGRectMake(50, 0, JX_SCREEN_WIDTH-100, 30)
                               ];
    bilateralSld.maximumValue = 6;
    [bilateralSld addTarget:self action:@selector(bilateralFilter:) forControlEvents:UIControlEventValueChanged];
    [_bottomControlView addSubview:bilateralSld];
    _bilateralSld = bilateralSld;
    
    //美白
    UILabel *brightnessL = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 40, 25)];
    brightnessL.text = @"JX_CameraWhitening";
    brightnessL.font = [UIFont systemFontOfSize:14];
    brightnessL.textColor = [UIColor whiteColor];
    [_bottomControlView addSubview:brightnessL];
    
    UISlider *brightnessSld  = [[UISlider alloc] initWithFrame:CGRectMake(50, 40, JX_SCREEN_WIDTH-100, 30)
                                ];
    brightnessSld.minimumValue = 0;
    brightnessSld.maximumValue = 0.1;
    [brightnessSld addTarget:self action:@selector(brightnessFilter:) forControlEvents:UIControlEventValueChanged];
    [_bottomControlView addSubview:brightnessSld];
    _brightnessSld = brightnessSld;
}

//点击滤镜
- (void)didFilterBtn {
    [self setupBeautyView:YES];
}
//点击美颜
- (void)didBeautyBtn {
    [self setupBeautyView:NO];
}

#pragma mark - 调整磨皮
- (void)bilateralFilter:(UISlider *)slider {
    [self recoverFilterGroup];
    //值越小，磨皮效果越好
    [_bilateralFilter setDistanceNormalizationFactor:[self getBilValue:slider.value]];
    self.bilHis = slider.value;
    NSLog(@"------调整磨皮 = %f - %f - %f",[self getBilValue:slider.value],(ldexp(slider.value, 10)),slider.value);
}

#pragma mark - 调整亮度
- (void)brightnessFilter:(UISlider *)slider {
    [self recoverFilterGroup];
    _brightnessFilter.brightness = slider.value;
    self.briHis = slider.value;
    NSLog(@"------调整亮度 = %f",slider.value);
}

// 恢复调整状态下的磨皮和亮度
- (void)recoverFilterGroup {
    if (self.isCreateFilter) {
        [_videoCamera removeAllTargets];
        [self setFilterGroup];
        self.isCreateFilter = NO;
        UIView *view = _photoStyleImages[1];
        for (UIImageView *imageView in _photoStyleImages) {
            if (view == imageView) {
                imageView.layer.borderWidth = 2.0;
                imageView.layer.borderColor = [[UIColor yellowColor] CGColor];
            }else {
                imageView.layer.borderWidth = 0.0;
            }
        }
        
    }
}


- (CGFloat)getBilValue:(CGFloat)value {
    CGFloat maxValue = 10;
    CGFloat va = maxValue - value;
    va = 60000 / (ldexp(value, 10));
    return va;
}

- (void)hideBaseView {
    self.baseView.hidden = YES;
}

- (void)clickBigView {}

+ (void)addWaterMarkTypeWithCorAnimationAndInputVideoURL:(NSURL*)InputURL WithCompletionHandler:(void (^)(NSURL* outPutURL, int code))handler{
    NSDictionary *opts = [NSDictionary dictionaryWithObject:@(YES) forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVAsset *videoAsset = [AVURLAsset URLAssetWithURL:InputURL options:opts];    AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];    AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];    NSError *errorVideo = [NSError new];    AVAssetTrack *assetVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo]firstObject];    CMTime endTime = assetVideoTrack.asset.duration;    BOOL bl = [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, assetVideoTrack.asset.duration)
                                  ofTrack:assetVideoTrack
                                   atTime:kCMTimeZero error:&errorVideo];
    videoTrack.preferredTransform = assetVideoTrack.preferredTransform;    NSLog(@"errorVideo:%ld%d",errorVideo.code,bl);    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *documentsDirectory = [paths objectAtIndex:0];    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *outPutFileName = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mov",outPutFileName]];    NSURL* outPutVideoUrl = [NSURL fileURLWithPath:myPathDocs];
    CGSize videoSize = [videoTrack naturalSize];
    UIFont *font = [UIFont systemFontOfSize:60.0];    CATextLayer *aLayer = [[CATextLayer alloc] init];
    [aLayer setFontSize:60];
    [aLayer setString:@"H"];
    [aLayer setAlignmentMode:kCAAlignmentCenter];
    [aLayer setForegroundColor:[[UIColor greenColor] CGColor]];
    [aLayer setBackgroundColor:[UIColor clearColor].CGColor];    CGSize textSize = [@"H" sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    [aLayer setFrame:CGRectMake(240, 470, textSize.width, textSize.height)];
    aLayer.anchorPoint = CGPointMake(0.5, 1.0);
    CATextLayer *bLayer = [[CATextLayer alloc] init];
    [bLayer setFontSize:60];
    [bLayer setString:@"E"];
    [bLayer setAlignmentMode:kCAAlignmentCenter];
    [bLayer setForegroundColor:[[UIColor greenColor] CGColor]];
    [bLayer setBackgroundColor:[UIColor clearColor].CGColor];    CGSize textSizeb = [@"E" sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    [bLayer setFrame:CGRectMake(240 + textSize.width, 470 , textSizeb.width, textSizeb.height)];
    bLayer.anchorPoint = CGPointMake(0.5, 1.0);
    CATextLayer *cLayer = [[CATextLayer alloc] init];
    [cLayer setFontSize:60];
    [cLayer setString:@"L"];
    [cLayer setAlignmentMode:kCAAlignmentCenter];
    [cLayer setForegroundColor:[[UIColor greenColor] CGColor]];
    [cLayer setBackgroundColor:[UIColor clearColor].CGColor];    CGSize textSizec = [@"L" sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    [cLayer setFrame:CGRectMake(240 + textSizeb.width + textSize.width, 470 , textSizec.width, textSizec.height)];
    cLayer.anchorPoint = CGPointMake(0.5, 1.0);
    CATextLayer *dLayer = [[CATextLayer alloc] init];
    [dLayer setFontSize:60];
    [dLayer setString:@"L"];
    [dLayer setAlignmentMode:kCAAlignmentCenter];
    [dLayer setForegroundColor:[[UIColor greenColor] CGColor]];
    [dLayer setBackgroundColor:[UIColor clearColor].CGColor];    CGSize textSized = [@"L" sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    [dLayer setFrame:CGRectMake(240 + textSizec.width+ textSizeb.width + textSize.width, 470 , textSized.width, textSized.height)];
    dLayer.anchorPoint = CGPointMake(0.5, 1.0);
    CATextLayer *eLayer = [[CATextLayer alloc] init];
    [eLayer setFontSize:60];
    [eLayer setString:@"O"];
    [eLayer setAlignmentMode:kCAAlignmentCenter];
    [eLayer setForegroundColor:[[UIColor greenColor] CGColor]];
    [eLayer setBackgroundColor:[UIColor clearColor].CGColor];    CGSize textSizede = [@"O" sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    [eLayer setFrame:CGRectMake(240 + textSized.width + textSizec.width+ textSizeb.width + textSize.width, 470 , textSizede.width, textSizede.height)];
    eLayer.anchorPoint = CGPointMake(0.5, 1.0);    CABasicAnimation* basicAni = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    basicAni.fromValue = @(0.2f);
    basicAni.toValue = @(1.0f);
    basicAni.beginTime = AVCoreAnimationBeginTimeAtZero;
    basicAni.duration = 2.0f;
    basicAni.repeatCount = HUGE_VALF;
    basicAni.removedOnCompletion = NO;
    basicAni.fillMode = kCAFillModeForwards;
    [aLayer addAnimation:basicAni forKey:nil];
    [bLayer addAnimation:basicAni forKey:nil];
    [cLayer addAnimation:basicAni forKey:nil];
    [dLayer addAnimation:basicAni forKey:nil];
    [eLayer addAnimation:basicAni forKey:nil];
    CALayer *parentLayer = [CALayer layer];    CALayer *videoLayer = [CALayer layer];
    parentLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
    videoLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
    [parentLayer addSublayer:videoLayer];
    [parentLayer addSublayer:aLayer];
    [parentLayer addSublayer:bLayer];
    [parentLayer addSublayer:cLayer];
    [parentLayer addSublayer:dLayer];
    [parentLayer addSublayer:eLayer];    AVMutableVideoComposition* videoComp = [AVMutableVideoComposition videoComposition];
    videoComp.renderSize = videoSize;
    parentLayer.geometryFlipped = true;
    videoComp.frameDuration = CMTimeMake(1, 30);
    videoComp.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];    AVMutableVideoCompositionInstruction* instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
     
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, endTime);    AVMutableVideoCompositionLayerInstruction* layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
    instruction.layerInstructions = [NSArray arrayWithObjects:layerInstruction, nil];
    videoComp.instructions = [NSArray arrayWithObject: instruction];
     
    AVAssetExportSession* exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition
                                                                      presetName:AVAssetExportPresetHighestQuality];
    exporter.outputURL=outPutVideoUrl;
    exporter.outputFileType = AVFileTypeMPEG4;
    exporter.shouldOptimizeForNetworkUse = YES;
    exporter.videoComposition = videoComp;
    [exporter exportAsynchronouslyWithCompletionHandler:^{        dispatch_async(dispatch_get_main_queue(), ^{            //这里是输出视频之后的操作，做你想做的
            NSLog(@"输出视频地址:%@ andCode:%@",myPathDocs,exporter.error);
            handler(outPutVideoUrl,(int)exporter.error.code);
        });
    }];
}

@end
